package tcpSocket;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 线程类：对每一个客户请求都要创建一个响应的线程
 * @author yy
 *
 */

public class LoginThread extends Thread {
	private Socket socket;

	public LoginThread() {
		super();
	}

	public LoginThread(Socket socket) {
		super();
		this.socket = socket;
	}
	
	public void run(){
		try {
			// 获得输入流，得到用户的请求
			InputStream is = socket.getInputStream();
			ObjectInputStream ois = new ObjectInputStream(is);
			User user = (User)ois.readObject();
			System.out.println("我是服务器，我接收到的信息是：" + user.getUserName() + "-" + user.getPassword());
			
			// 得到客户端的ip
			InetAddress ia = socket.getInetAddress();
			String ip = ia.getHostAddress();
			System.out.println("相应客户端的ip是：" + ip);
			
			// 给客户端一个响应
			OutputStream os = socket.getOutputStream();
			String reply = "欢迎登陆";
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
			bw.write(reply);
			bw.flush();
			
			//释放资源
			bw.close();
			os.close();
			ois.close();
			is.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

	}
	

}
